package com.hcc.gateway.netty.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.hcc.gateway.common.utils.AppCtxUtils;
import com.hcc.gateway.netty.config.GatewayConfig;
import com.hcc.gateway.netty.context.DefaultGatewayExchange;
import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.ReqContext;
import com.hcc.gateway.netty.context.RespContext;
import com.hcc.gateway.netty.exception.DefaultGatewayExceptionHandler;
import com.hcc.gateway.netty.exception.GatewayExceptionHandler;
import com.hcc.gateway.netty.filter.GatewayFilter;
import com.hcc.gateway.netty.support.ByteBufUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网关处理入口
 *
 * @author hushengjun
 * @date 2021/12/26
 */
@Slf4j
public class GatewayServerHandler extends ChannelInboundHandlerAdapter {

    private final GatewayConfig config;

    public GatewayServerHandler(GatewayConfig config) {
        this.config = config;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;

        // 初始化请求上下文
        ReqContext reqContext = new ReqContext(fullHttpRequest);
        reqContext.setClientIp(this.getClientIp(ctx, fullHttpRequest));

        // 初始化响应上下文
        RespContext respContext = new RespContext();
        respContext.setHeaders(new DefaultHttpHeaders());

        // 初始化默认参数
        Map<String, Object> attributes = new HashMap<>();
        GatewayExchange gatewayExchange = new DefaultGatewayExchange(reqContext, respContext, attributes);

        // 初始化添加filter
        Map<String, GatewayFilter> beanMapFilterMap = AppCtxUtils.getBeansOfType(GatewayFilter.class);
        List<GatewayFilter> filters = new ArrayList<>(beanMapFilterMap.values());

        // 执行过滤器链路
        GatewayFilterHandler container = new GatewayFilterHandler(filters);
        try {
            container.handle(gatewayExchange);
        } catch (Throwable t) {
            this.exceptionHandle(ctx, gatewayExchange, t);
            return;
        }

        // 获取http响应
        FullHttpResponse fullHttpResponse = this.getFullHttpResponse(respContext);

        ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
    }

    /**
     * 获取客户端ip
     * @param ctx
     * @param fullHttpRequest
     * @return
     */
    private String getClientIp(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) {
        String clientIp = fullHttpRequest.headers().get("X-Forwarded-For");
        if (StrUtil.isEmpty(clientIp)) {
            InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
            clientIp = inetSocketAddress.getAddress().getHostAddress();
        }

        return clientIp;
    }

//    /**
//     * 匹配路由
//     * @param uri
//     * @return
//     */
//    private GatewayRoute matchRoute(String uri) {
//        // TODO 考虑使用正则匹配？
//        RouteDefinitionLocator routeDefinitionLocator;
//        try {
//            routeDefinitionLocator = AppCtxUtils.getBean(RouteDefinitionLocator.class);
//        } catch (Exception e) {
//            return null;
//        }
//
//        List<RouteDefinition> routeDefinition = routeDefinitionLocator.getGatewayRouteDefinition();
//        List<GatewayRoute> routes = new ArrayList<>();
//        for (GatewayRoute route : routes) {
//            List<Predicate<GatewayExchange>> predicates = route.getPredicates();
//            for (Predicate<GatewayExchange> predicate : predicates) {
//                predicate.test();
//            }
//        }
//
//        if (CollectionUtil.isEmpty(routes)) {
//            return null;
//        }
//
//        GatewayRoute gatewayRoute = routes.get(0);
//        log.info("路由信息：{}", gatewayRoute);
//
//        return gatewayRoute;
//    }

    /**
     * 获取http响应
     * @param respContext
     * @return
     */
    private FullHttpResponse getFullHttpResponse(RespContext respContext) {
        ByteBuf body = respContext.getBody();
        // body为空则写一个空字符回去
        if (body == null) {
            body = ByteBufUtils.writeStringToByteBuf("");
            if (respContext.getHttpStatus() == null) {
                respContext.setHttpStatus(HttpResponseStatus.NO_CONTENT);
            }
        }
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, respContext.getHttpStatus(), body);

        if (CollectionUtil.isNotEmpty(respContext.getHeaders())) {
            response.headers().add(respContext.getHeaders());
        }
        response.headers().setInt("Content-Length", response.content().readableBytes());

        return response;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
        log.error("网关异常", cause);
    }

    /**
     * 执行链路异常处理
     * @param ctx
     * @param exchange
     * @param t
     */
    private void exceptionHandle(ChannelHandlerContext ctx, GatewayExchange exchange, Throwable t) {
        GatewayExceptionHandler handler;
        // 用户未定义异常处理器时使用默认异常处理器
        try {
            handler = AppCtxUtils.getBean(GatewayExceptionHandler.class);
        } catch (Exception e) {
            handler = new DefaultGatewayExceptionHandler();
        }

        handler.handle(exchange, t);

        RespContext respContext = exchange.getRespContext();
        FullHttpResponse fullHttpResponse = this.getFullHttpResponse(respContext);
        ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
    }

}
